<template>
  <basic-container>
    <div class="container">
      <!--头部搜索部分-->
      <div class="merchant" style="display: inline-block">
        选择供应商家：
        <el-select
          filterable
          remote
          :remote-method="remoteMerchant"
          v-model="merchantId"
          @change="changeMerchant"
          placeholder="请选择">
          <el-option
            v-for="(item,index) in merchantList"
            :key="index"
            :label="item.merchantName"
            @change="changeMerchant"
            :value="item.merchantId"/>
        </el-select>
      </div>
      <div class="shop" style="display: inline-block;margin-left: 20px">
        选择店铺：
        <el-select
          filterable
          remote
          :remote-method="remoteShop"
          v-model="shopId"
          @change="changeShop"
          placeholder="请选择">
          <el-option
            v-for="(item,index) in shopList"
            :key="index"
            :label="item.name"
            @change="changeShop"
            :value="item.shopId"/>
        </el-select>
      </div>
      <div class="search-wrap">
        <el-input placeholder="请输入内容" v-model="searchText" width="286" clearable>
          <el-select v-model="searchSelect" slot="prepend" placeholder="请选择" class="search">
            <el-option label="商品编号" value="1"></el-option>
            <el-option label="商品名称" value="2"></el-option>
          </el-select>
        </el-input>
        <el-select v-model="modelStatus" slot="prepend" style="margin-left: 10px; width: 120px;" placeholder="是否启用多规格">
          <el-option label="全部规格" value=""></el-option>
          <el-option label="多规格" value="1"></el-option>
          <el-option label="单规格" value="0"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="searchGoodsList" class="search-btn">搜索</el-button>
        <el-button type="default" size="small" @click="resetGoodsList">清除条件</el-button>
        <div class="tool-btns">
          <el-button type="primary" @click="turnToAddGoods">新增商品</el-button>
          <el-button type="primary" @click="toCSale" :disabled="toSaleBtnFlag">一键同步商城</el-button>
        </div>
      </div>
      <el-container>
        <el-header class="header-nav">
          <el-tabs v-model="activeTab" @tab-click="changeTab" style="margin-left: 10px;">
            <el-tab-pane label="全部" name="0"></el-tab-pane>
            <el-tab-pane label="在售中" name="1"></el-tab-pane>
            <el-tab-pane label="已售罄" name="2"></el-tab-pane>
            <el-tab-pane label="已下架" name="3"></el-tab-pane>
          </el-tabs>
        </el-header>
        <el-container>
          <el-container>
            <el-aside width="220px" class="aside-nav">
              <avue-tree
                :option="categoryOption"
                :data="goodsCategories"
                @node-click="getCategoryGoods"
              >
              </avue-tree>
            </el-aside>
            <el-main class="goods-info-table">
              <avue-crud ref="crud" :data="goodsList" :option="tableOption" @row-del="handleDelete">

                <template slot-scope="scope" slot="sort">
                  <input-box :changeValue="scope.row.sort"
                             :goodsName="scope.row.goodsName"
                             :goods-id="scope.row.goodsId"
                             :type="1"
                             title="修改权重值"
                             @refresh="refresh"
                  ></input-box>
                </template>

                <template slot-scope="scope" slot="storage">
                  <input-box :changeValue="scope.row.storage"
                             :goodsName="scope.row.goodsName"
                             :goods-id="scope.row.goodsId"
                             :type="2"
                             title="修改库存"
                             @refresh="refresh"
                  ></input-box>
                </template>

                <template slot-scope="scope" slot="modelPrice">
                    <div v-for="(item,index) in scope.row.modelList" :key="index">
                      <p>{{item.modelName}}：¥{{item.modelPrice}}</p>
                    </div>
                </template>

                <template slot-scope="scope" slot="isMarketable">
                  <el-switch
                    v-model="scope.row.isMarketable"
                    :active-value= "'1'"
                    :inactive-value= "'0'"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="marketTable(scope.row)"
                  >
                  </el-switch>
                </template>

                <template slot-scope="scope" slot="salecFlag">
                  <el-switch
                    v-model="scope.row.salecFlag"
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="onOrOff(scope.row.salecFlag,scope.row.goodsId)"
                  >
                  </el-switch>
                </template>
                <template slot-scope="scope" slot="menu">
                  <el-button type="text" icon="el-icon-edit" @click="jumpToEidt(scope.row)">编辑</el-button>
                  <el-button type="text" @click="jumpToDetail(scope.row)">详情</el-button>
                </template>
              </avue-crud>
            </el-main>
          </el-container>
        </el-container>
        <el-footer style="margin-top: 10px">
          <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page.sync="currentPage" :page-sizes="[10, 20, 40, 60]" :page-size="10"
                           background :layout="layout" :total="totalCount">
            </el-pagination>
          </div>
        </el-footer>
      </el-container>

    </div>
    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleDelete">确 定</el-button>
            </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import request from '../request.js'
  import router from "@/router/router"
  import {
    toSaleC,
    onSale,
    offSale
  } from "../../../api/salec/salecproduct";
  import {getmerchantList} from "../../../api/supply/supplier"
  import {fetchList} from "../../../api/manage/shop";
  import {getCategoryTree} from "../../../api/goods/goodscategory";
  import {getGoodsList} from '../../../api/goods/goods'
  import {delGoods, isMarketTable} from '../../../api/supply/suppliergoods'

  import inputBox from "../../../supply/supplygoods/component/inputBox";

  import {tableoption} from '../../../const/crud/pds/goods/salecGoods'
  export default {
    name: "goodsList",
    components: {
      inputBox
    },
    data() {
      return {
        request: new request(),
        // request数据
        goodsCategories: [],
        tableOption: tableoption,
        goodsList: [],
        /**
         * 状态, 中间变量
         */
        activeTab: '0',
        loading: true,
        multipleSelection: [],
        isDelAll: false,
        delVisible: false,
        collapse: false,
        totalCount: 10,
        currentPage: 1,
        pageSize: 10,
        layout: "total, sizes, prev, pager, next, jumper",
        categoryId: '',
        searchText: '',
        searchSelect: '2',
        windowHeight: '600',
        toSaleBtnFlag: false,
        modelStatus: '',
        menuActiveIndex: '',
        merchantList: '',
        merchantId: '',
        shopList: '',
        shopId: '',
        categoryOption: {
          defaultExpandAll:true,
          addBtn: false,
          props:{
            label: 'name',
            value: 'id',
            children: 'children'
          }
        }
      }
    },
    created() {
      this.getmerchantList({status: 2})
    },
    methods: {
      jumpToEdit(row) {
        let query = {goodsSn: row.goodsSn};
        this.$router.push({path: '/goods/editGoods', query: query})
      },
      /**
       * 请求方法
       */
      // 获取表格数据
      getTableData(params = {}) {
        let goodsStatus = ''
        if (this.activeTab === '0') {
          goodsStatus = ""
        }
        if (this.activeTab === '1') {
          goodsStatus = 0
        }
        if (this.activeTab === '2') {
          goodsStatus = 2
        }
        if (this.activeTab === '3') {
          goodsStatus = 1
        }
        params.goodsStatus = goodsStatus
        params.shopId = this.shopId
        params.current = this.currentPage
        params.size = params.pageSize || this.pageSize
        params.categoryId = this.categoryId
        getGoodsList(params).then(res => {
          console.log(res);
          this.totalCount = res.data.data.total
          this.goodsList = res.data.data.records
        })
      },
      // 获取商品分类列表
      getGoodsCategoryList(param = {}) {
        getCategoryTree({shopId: this.shopId}).then(res => {
          // console.log(res.data.data);
          this.goodsCategories = res.data.data
        })
      },
      getCategoryGoods(categoryId) {
        let params = {}
        // params.pageNo = this.currentPage
        this.categoryId = categoryId.id
        this.loading = true
        this.getTableData(params)
      },
      selectCategoryGoods(index, path) {
        this.menuActiveIndex = index;
        this.getCategoryGoods(index);
      },
      // 获取供应商的商家列表
      getmerchantList(param = {}) {
        getmerchantList(param).then(res => {
          // console.log(res);
          this.merchantList = res.data.data.records
          this.merchantId = this.toMerchantId || res.data.data.records[0].merchantId
          this.getShopList()
        })
      },
      remoteMerchant(name = null) {
        let query = {
          merchantName: name,
          status: 2
        };
        getmerchantList(query).then(res => {
          this.merchantList = res.data.data.records;
        });
      },
      //获取店铺列表
      getShopList() {
        let params = {}
        params.current = this.currentPage
        params.size = this.pageSize
        params.status = 2
        params.merchantId = this.merchantId
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
          console.log(this.shopList);
          this.shopId = this.toShopId || res.data.data.records[0].shopId
          getCategoryTree({shopId: res.data.data.records[0].shopId}).then(res => {
            this.goodsCategories = res.data.data
          })
          this.getTableData()
        })
      },
      remoteShop(name = null) {
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          this.shopList = res.data.data.records
        })
      },
      //改变merchantId
      changeMerchant() {
        this.categoryId = ''
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          status: 2,
          merchantId: this.merchantId,
          name: name
        }
        fetchList(params).then(res => {
          if (res.data.data.records.length == 0) {
            this.$message.warning("没有店铺")
          }
          this.shopList = res.data.data.records
          setTimeout(() => {
            this.shopId = this.shopList[0].shopId
            this.getTableData()
            this.getGoodsCategoryList()
          },100)

        })
      },
      //改变shopID
      changeShop() {
        this.getTableData()
        this.getGoodsCategoryList()
      },
      /**
       * 页面相关方法
       */
      searchGoodsList() {
        this.loading = true
        this.menuActiveIndex = ''
        this.categoryId = ''
        let params = {}
        let searchSelect = this.searchSelect
        if (searchSelect === '1') {
          params.goodsSn = this.searchText
        }
        if (searchSelect === '2') {
          params.goodsName = this.searchText
        }
        params.modelStatus = this.modelStatus;
        params.pageNo = this.currentPage
        this.getTableData(params)
      },
      resetGoodsList() {
        this.loading = true
        this.activeTab = '0'
        this.categoryId = ''
        this.searchText = ''
        this.modelStatus = ''
        this.searchSelect = '2'
        this.currentPage = 1
        this.menuActiveIndex = ''
        let params = {}
        params.pageNo = this.currentPage
        this.getTableData(params)
      },
      changeTab(tab) {
        this.activeTab = tab.name
        this.loading = true
        let params = {}
        let searchSelect = this.searchSelect
        if (searchSelect === '1') {
          params.goodsSn = this.searchText
        }
        if (searchSelect === '2') {
          params.goodsName = this.searchText
        }
        params.pageNo = this.currentPage
        this.getTableData(params)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleGoodsCommand(command) {
        if (command.type == 'delete') {
          this.delVisible = true
          this.delItem = command.row,
            this.delIndex = command.index
        }
        if (command.type == 'deleteAll') {
          this.delVisible = true
          this.isDelAll = true
        }
        if (command.type == 'handleMarketable') {
          this.handleMarketable(1)
        }
        if (command.type == 'handleDisMarketable') {
          this.handleMarketable(0)
        }
        if (command.type == 'marketable') {
          this.changeMarketable(1, command.row.goodsSn)
        }
        if (command.type == 'disMarketable') {
          this.changeMarketable(0, command.row.goodsSn)
        }
      },
      /**
       * 商品管理
       */
      // 新增
      turnToAddGoods() {
        router.push({path: '/goods/addGoods'})
      },
      //刷新
      refresh() {
        this.getTableData()
      },
      // 删除
      handleDelete(row) {
        console.log(row);
        console.warn("删除")
        const goodsId = row.goodsId
        delGoods(goodsId).then(res => {
          this.$message.success("删除商品成功")
          this.getTableData()
        })
      },
      // 下架
      marketTable(val) {
        let marketable = ''
        console.log(val);
        if(val.isMarketable == '1') {
          marketable = true
        }else {
          marketable = false
        }
        let params = {
          goodsId: val.goodsId,
          marketable: marketable
        }
        isMarketTable(params).then(res => {
          if(val.isMarketable == '1') {
            this.$message.success("上架成功")
          }
          if(val.isMarketable == '0') {
            this.$message.success("下架成功")
          }
        })
      },
      /**
       * 分类
       */

      /**
       * 分页
       */
      handleSizeChange(size) {
        this.pageSize = size
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.currentPage = page
        this.getTableData()
      },
      /**
       * 一键添加到C端
       */
      toCSale() {
        this.toSaleBtnFlag = true;
        toSaleC().then(res => {
          if (res.code = 200) {
            this.$message.success('同步成功')
          } else {
            this.$message.error('同步失败')
          }
          this.toSaleBtnFlag = false;
        })
      },
      on(req) {
        onSale(req).then(res => {
          if (res.code = 200) {
            this.$message.success('上架成功')
          } else {
            this.$message.error('上架失败')
          }
        })
      },
      off(req) {
        offSale(req).then(res => {
          if (res.code = 200) {
            this.$message.success('下架成功')
          } else {
            this.$message.error('下架失败')
          }
        })
      },
      onOrOff(status, goodsId) {
        console.log(goodsId);
        console.log(status);
        let req = {
          goodsIds: [
            goodsId
          ]
        }
        if (status == 0) {
          this.off(req);
        } else if (status = 1) {
          this.on(req);
        }
      }
    }
  };
</script>

<style scoped>
  .table {
    width: 100%;
    position: relative;
  }

  .search {
    /*float: left;*/
    font-size: 13px;
    width: 100px;
  }

  .el-header {
    padding-left: 0;
    padding-right: 0;
  }

  .tool-btns {
    float: right;
    margin-right: 30px;
    display: inline-block;
  }

  .menu-title {
    display: flex;
    justify-content: space-between;
    width: 200px;
    padding: 15px 20px;
    background: #f0f0f0;
    box-sizing: border-box;
  }

  .btn-group {
    flex: 1;
    padding: 20px;
  }

  /* .btn-group button {
          margin-right: 8px;
      } */
  /* 商品分类 */
  .goods-category:not(.el-menu--collapse) {
    /*width: 180px;*/
    border-bottom: 1px solid #e6e6e6;
  }

  .goods-category.el-menu--collapse {
    width: 0;
    border-right: 0;
  }

  /* 商品列表 */
  .goods-cover {
    display: inline-block;
    width: 60px;
    height: 60px;
  }

  .search-wrap {
    text-align: right;
    position: relative;
    text-align: left;
    height: 70px;
    line-height: 70px;
    padding-left: 10px;
  }

  .search-btn {
    margin-left: 10px;
  }

  /* 覆盖框架原生样式 */
</style>
<style>
  .search-wrap .el-select .el-input {
    width: 105px;
  }

  .search-wrap .el-input-group__prepend {
    background-color: #fff;
  }

  .search-wrap .el-input-group {
    width: 25%;
  }

  .search-category {
    font-size: 12px;
    width: 80px;
  }

  .aside-nav {
    height: calc(100vh - 330px);
    text-align: left;
  }
</style>

